package com.k8.rpc.metadata;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@Data
@Accessors(chain = true)
public class AppMetaData implements Serializable {
    private Long serviceInstanceId;
    private String ip;
    private Integer port;
    private Map<String, ProtocolMetadata> protocols;
    private String host;

    /**
     * 将host解析为IP，若解析失败则默认使用localhost
     *
     * @param host 主机名或IP地址
     * @return 当前AppMetaData实例（链式调用）
     */
    public AppMetaData setHost(String host) {
        if (host == null || host.trim().isEmpty()) {
            this.ip = "localhost";
            return this;
        }
        try {
            // 解析host为InetAddress，自动处理IP地址和主机名
            InetAddress inetAddress = InetAddress.getByName(host.trim());
            this.ip = inetAddress.getHostAddress(); // 获取IP地址字符串
        } catch (UnknownHostException e) {
            this.ip = "localhost";
        }
        return this;
    }

}
